package com.ftqh.project.travel.controller;

import com.ftqh.project.travel.notes.entity.Note;
import com.ftqh.project.travel.notes.entity.NoteImage;
import com.ftqh.project.travel.notes.service.NoteImageService;
import com.ftqh.project.travel.notes.service.NoteService;
import com.ftqh.project.travel.security.entity.User;
import com.ftqh.project.travel.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by Administrator on 2017/5/8.
 */
@RestController
@RequestMapping("notes")
public class NoteController {
    @Autowired
    NoteService noteService;
    @Autowired
    UserService userService;
    @Autowired
    NoteImageService noteImageService;
    @GetMapping("")
    public List<Note> findAll(){
        return noteService.findAll();
    }
    @GetMapping("{id}")
    public Note findById(@PathVariable("id") Long id){
        Optional<Note> note = noteService.findById(id);
        if(note.isPresent()){
            return note.get();
        }
        return null;
    }
    @PostMapping("")
    public Integer save(Note note){
        //获取当前用户名
        String authorName = SecurityContextHolder.getContext().getAuthentication().getName();
        Optional<User> user = userService.findByUsername(authorName);
        note.setAuthorName(authorName);
        note.setAuthor(user.get());
        noteService.save(note);
        //更新图片的travel_note_id
        List<Long> imageIds = getImageIds(note.getContent());

        imageIds.stream().forEach(id->{
           Optional<NoteImage> noteImage =  noteImageService.findById(id);
           noteImage.ifPresent(image->{
               if(null == image.getNoteId()){
                   noteImageService.updateNoteId(id,note.getId());
               }
           });
        });

        return 1;
    }

    /**
     * 从游记内容(content)中获取图片id
     * @param content
     * @return
     */
    private List<Long> getImageIds(String content){
        String searchPrefix = "<img id=\"xmTanImg_";
        String searchPostfix = "\" name=\"xmTanImg_";
        List<Long> ids = new ArrayList<>();
        int start = 0;
        do {
            start = content.indexOf(searchPrefix,start);
            if(start>=0){
                start += searchPrefix.length();
                int end = content.indexOf(searchPostfix,start);
                ids.add(Long.valueOf(content.substring(start,end)));
                start = end;
            }
        }while(start>=0);
        return ids;
    }
}
